<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row>
        <el-col :span="4">
          <el-button type="success" plain>添加角色</el-button>
        </el-col>
      </el-row>
      <template>
        <el-table :data="roleList" border stripe style="width: 100%">
          <!-- 展开列 -->
          <el-table-column align="center" type="expand">
            <template slot-scope="scope">
              {{ scope.row }}
              <el-row
                :class="['vcenter', 'border-b', i1 === 0 ? 'border-t' : '']"
                v-for="(item1, i1) in scope.row.children"
                :key="item1.id"
              >
                <!-- 渲染一级权限 -->
                <el-col :span="5">
                  <el-tag
                    @close="removeRightById(scope.row, item1.id)"
                    closable
                    >{{ item1.authName }}</el-tag
                  >
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 渲染二，三级权限 -->
                <el-col :span="19">
                  <el-row
                    :class="['vcenter', i2 === 0 ? '' : 'border-t']"
                    v-for="(item2, i2) in item1.children"
                    :key="item2.id"
                  >
                    <el-col :span="6">
                      <el-tag
                        @close="removeRightById(scope.row, item2.id)"
                        closable
                        type="success"
                        >{{ item2.authName }}</el-tag
                      >
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="18">
                      <el-tag
                        @close="removeRightById(scope.row, item3.id)"
                        closable
                        type="danger"
                        v-for="item3 in item2.children"
                        :key="item3.id"
                        >{{ item3.authName }}</el-tag
                      >
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <!-- 索引列 -->
          <el-table-column align="center" label="*" type="index">
          </el-table-column>
          <el-table-column align="center" label="角色名称" prop="roleName">
          </el-table-column>
          <el-table-column align="center" label="角色描述" prop="roleDesc">
          </el-table-column>
          <el-table-column align="center" label="操作">
            <!-- 插槽渲染按钮 -->
            <template slot-scope="scope">
              <el-button size="mini" plain type="primary" icon="el-icon-edit"
                >编辑</el-button
              >
              <el-button size="mini" plain type="danger" icon="el-icon-delete"
                >删除</el-button
              >
              <el-button
                size="mini"
                plain
                type="warning"
                icon="el-icon-setting"
                @click="setRightHandle(scope.row)"
                >分配权限</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightsDialogVisible"
      width="50%"
      @close="hideSetRightDialog"
    >
    <!-- data数据源，props按照哪种格式渲染数据 -->
    <!-- show-checkbox显示复选框 -->
    <!-- node-key每个树节点用来作为唯一标识的属性 -->
    <!-- default-expand-all展开所有节点 -->
    <!-- default-checked-keys展开的节点的 key 的数组 -->
      <el-tree
        :data="rightList"
        :props="treeProps"
        ref="rightRef"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys">
       </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data () {
    return {
      // 角色列表
      // 凡是data数据都具有响应式
      // Vue给每个data数据都添加了监控
      roleList: [], // 角色列表
      setRightsDialogVisible: false, // 分配权限显示隐藏
      rightList: [], // 权限列表
      treeProps: {
        label: 'authName', // 渲染内容
        children: 'children' // 渲染结构
      },
      defKeys: [], // 默认选中节点ID
      roldId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 角色列表
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.roleList = res.data
    },
    // 删除指定权限
    async removeRightById (role, rightId) {
      console.log(role === this.roleList[0])
      const confirmRes = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      if (confirmRes !== 'confirm') {
        return this.$message.error('取消删除权限！')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败！')
      }
      this.$message.success('删除成功！')
      role.children = res.data
      console.log(confirmRes)
    },
    // 显示修改权限弹框
    async setRightHandle (role) {
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.rightList = res.data
      // 获取父级id
      this.roldId = role.id
      // 调用递归
      this.getLefKey(role, this.defKeys)
      this.setRightsDialogVisible = true
    },
    // 递归node数据，arr ->defkeys
    getLefKey (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      // 包含children属性，进行遍历

      node.children.forEach(item => this.getLefKey(item, arr))
    },
    // 关闭弹框清空数组
    hideSetRightDialog () {
      this.defKeys = []
    },
    // 点击分配权限
    async allotRights () {
      const keys = [
        ...this.$refs.rightRef.getCheckedKeys(),
        ...this.$refs.rightRef.getHalfCheckedKeys()
      ]
      const newKeys = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roldId}/rights`,
        { rids: newKeys })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('分配权限成功！')
      this.getRolesList()
      this.setRightsDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 10px;
}
.border-t {
  border-top: 1px solid #eee;
}
.border-b {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
